﻿namespace MSSqlSchemaDoc.Xslt
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;

    /// <summary>
    /// Custom XML resolver.
    /// </summary>
    public class XslCustomResolver : XmlResolver
    {
        /// <summary>
        /// Dictionary of possible stylesheets.
        /// </summary>
        private IDictionary<string, XmlDocument> stylesheets;

        /// <summary>
        /// Initializes a new instance of the XslCustomResolver class.
        /// </summary>
        public XslCustomResolver()
        {
            this.stylesheets = new Dictionary<string, XmlDocument>();
        }

        /// <summary>
        /// Sets the credentials - not implemented.
        /// </summary>
        public override System.Net.ICredentials Credentials
        {
            set { throw new NotImplementedException(); }
        }

        /// <summary>
        /// Adds a stylesheet to the collection.
        /// </summary>
        /// <param name="name">The key of the stylesheet - its name without a path or extension.</param>
        /// <param name="stylesheet">The stylesheet.</param>
        public void AddStylesheet(string name, XmlDocument stylesheet)
        {
            this.stylesheets.Add(name, stylesheet);
        }

        /// <summary>
        /// Retrieves a stylesheet.
        /// </summary>
        /// <param name="name">The key of the stylesheet.</param>
        /// <returns>The XmlDocument.</returns>
        public XmlDocument RetrieveStylesheet(string name)
        {
            if (this.stylesheets.ContainsKey(name))
            {
                return this.stylesheets[name];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the appropriate XSL stylesheet.
        /// </summary>
        /// <param name="absoluteUri">The stylesheet to retrieve.</param>
        /// <param name="role">The parameter is not used.</param>
        /// <param name="toReturn">The parameter is not used.</param>
        /// <returns>An XmlTextReader object.</returns>
        public override object GetEntity(Uri absoluteUri, string role, Type toReturn)
        {
            // Get the name of the stylesheet
            string key = Path.GetFileNameWithoutExtension(absoluteUri.AbsolutePath);
            return this.stylesheets[key];
        }
    }
}
